package com.tong.ipprint.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.tong.ipprint.config.properties.IpPrintProperties;
import com.tong.ipprint.service.IpPrintService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: tong
 * @Date: 2024/07/28/16:26
 * @Description:
 */
public class IpPrintServiceImpl implements IpPrintService {
    @Resource
    private HttpServletRequest request;
    @Resource
    private IpPrintProperties ipPrintProperties;
    private Map<String, Integer> ipMap = new HashMap<>();

    @Override
    public void print() {
        // 获取ip
        String ip = request.getRemoteAddr();
        // 访问次数
        Integer count = ipMap.get(ip);
        count = ObjectUtil.isNull(count) ? 1 : count + 1;
        // 更新访问次数
        ipMap.put(ip, count);
        // 遍历打印
        ipMap.forEach((key, value) -> {
            // 如果是详细模式
            if (IpPrintProperties.Display.DETAILS.getValue().equals(ipPrintProperties.getDisplay())) {
                System.out.println("\t\t\tip访问监控");
                System.out.println("+---------ip---------+----count----+");
                System.out.println("|\t\t" + key + "\t\t\t" + value);
                System.out.println("+--------------------+-------------+");

            } else {
                // 如果是简易模式
                System.out.printf("ip:%s\t访问次数%s\n", key, value);
            }
        });
    }
}
